﻿namespace LiteBlog.Controllers
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Web.Mvc;
    using LiteBlog.Common;
    using LiteBlog.Components;
    using LiteBlog.Common.Entities;
    using LiteBlog.Components.Contracts;
    using System.Web.Script.Serialization;
    using LiteBlog.Controllers.Filters;
    using LiteBlog.Models;
    using LiteBlog.Controllers.Helpers;
    using LiteBlog.Common.Components;
    using System;
    using LiteBlog.Controllers.Contracts;

    public class ArchiveController : BaseController, IArchiveController
    {
        private IArchiveComp _archiveComponent;
        private IBlogComp _blogComp;
        private IPostComp _postComp;
        private IAuthorComp _authorComp;

        public IBlogComp BlogComponent
        {
            get
            {
                return _blogComp;
            }
        }
        public IPostComp PostComponent
        {
            get
            {
                return _postComp;
            }
        }
        public IAuthorComp AuthorComponent
        {
            get
            {
                return _authorComp;
            }
        }

        public ArchiveController(IArchiveComp archiveComponent, ISettingsComp settingsComp, ICacheComp cacheComp)
            : base(settingsComp, cacheComp)
        {
            _archiveComponent = archiveComponent;
        }

        public IArchiveComp ArchiveComponent
        {
            get { return _archiveComponent; }
        }

        public ActionResult Archive()
        {
            var posts = BlogComponent.GetPublished();

            IEnumerable<IGrouping<int, IGrouping<ArchiveMonth, PostInfo>>> model = default(IEnumerable<IGrouping<int, IGrouping<ArchiveMonth, PostInfo>>>);
            if (posts != null)
            {
                model = posts.GroupBy(p => new ArchiveMonth(p.Month, p.Year), ArchiveMonth.Comparer)
                             .GroupBy(group => group.Key.Year);
            }

            return View("Archive", GetSiteLayout(), model);
        }

        [ArchiveNotFoundFilter(Order = 1)]
        [CrawlerFilterForPosts(Order = 2)]
        public ActionResult Index(int year, int month, int? page)
        {
            ViewBag.Year = year;
            ViewBag.Month = month;

            var postInfos = BlogComponent.GetPostsByMonth(year, month);
            var postCollectionModel = new PostCollectionModel();

            var settings = GetSettings();
            int pageSize = settings.PostCount;
            page = page ?? 1;
            postCollectionModel.PageCount = 1;
            if (postInfos != null && postInfos.Count > 0)
                postCollectionModel.PageCount = postInfos.Count / pageSize + ((postInfos.Count % pageSize == 0) ? 0 : 1);
            page = Math.Min(page.Value, postCollectionModel.PageCount);
            int skip = (page.Value - 1) * pageSize;
            var posts = new List<Post>();
            if (postInfos != null && postInfos.Count > 0)
            {
                foreach (var postInfo in postInfos.Skip(skip).Take(pageSize))
                {
                    var post = PostComponent.Load(postInfo.FileID);
                    DisplayHelper.SetDisplayTime(post);
                    posts.Add(post);
                }
            }
            postCollectionModel.UrlType = UrlType.Archive;
            postCollectionModel.FilterId = string.Format("{0}/{1}", year, month);
            postCollectionModel.PostCollection = posts;
            if (RouteData != null)
                postCollectionModel.FilterName = (string)RouteData.Values["monthName"];
            postCollectionModel.Page = page.Value;

            // passing posts to CrawlerFilter
            if (RouteData != null)
                RouteData.Values["posts"] = postCollectionModel;

            if (UserModel != null && UserModel.Authenticated)
            {
                postCollectionModel.Author = AuthorComponent.Get(UserModel.Name);
            }

            return View("Index", GetSiteLayout(), postCollectionModel);
        }

        [HttpGet]
        public ActionResult GetMore(int year, int month, int page)
        {
            var postInfos = BlogComponent.GetPostsByMonth(year, month);
            var settings = GetSettings();
            int pageSize = settings.PostCount;
            int startIndex = page * pageSize;
            var posts = new List<Post>();
            if (postInfos != null && postInfos.Count > 0)
            {
                foreach (var postInfo in postInfos.Skip(startIndex).Take(pageSize))
                {
                    var post = PostComponent.Load(postInfo.FileID);
                    DisplayHelper.SetDisplayTime(post);
                    posts.Add(post);
                }
            }
            var resultModel = new ResultModel();
            resultModel.Result = posts.Count > 0 ? true : false;
            var resultModelWithData = new ResultModelWithData<List<Post>>(resultModel, posts);
            return this.Json(resultModelWithData, JsonRequestBehavior.AllowGet);
        }

        public void ResolveComponents()
        {

        }
    }
}